package com.cos.hospital.ui.main;

import android.Manifest;
import android.view.View;

import com.cos.hospital.R;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UToast;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

/**
 * 扫描二维码
 */
public class QRCodeActivity extends BaseActivity {
    @BindView(R.id.zxingview)
    ZXingView zXingView;

    @Override
    protected int layout() {
        return R.layout.activity_qrcode;
    }

    @Override
    protected void init() {
        setTitleLeftIcon();
        setTitleCenterTxt("扫描二维码");
    }

    @Override
    protected void logic() {
        zXingView.setDelegate(new QRCodeView.Delegate() {
            @Override
            public void onScanQRCodeSuccess(String result) {
                UToast.toast("识别结果：" + result);
            }

            @Override
            public void onScanQRCodeOpenCameraError() {
                USnackbar.showError(context, "打开相机出错");
            }
        });
        getPermissions();
    }

    private void getPermissions() {
        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.CAMERA)) {
            rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) {
                        startSpot();
                    } else {
                        MyUtil.getInstance().toSetting(context, "你已拒绝获取打开相机权限，为保证你能识别二维码，请开启该权限。", 10, true);
                    }
                });
        } else {
            startSpot();
        }
    }

    private void startSpot() {
        zXingView.startCamera();
        zXingView.startSpot();
    }

    @OnClick({R.id.title_back})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
        }
    }
}
